// miniprogram/pages/payOrder/payOrder.js
const app = getApp();
const AUTH_MODE = 'fingerPrint';
Page({

    /**
     * 页面的初始数据
     */
    data: {
        shopList: [],
        userAddress: [],
        selectIndex: "",
        totalPrice: null,
        userInfo: {},
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function(options) {
        if (options.orderShopList) {
            let shopList = JSON.parse(options.orderShopList)
            this.setData({
                shopList: shopList
            })
            let totalPrice = 0;
            for (let i = 0; i < shopList.length; i++) {
                totalPrice += (parseFloat(shopList[i].parameter.price) * parseInt(shopList[i].buyNumber))
            }
            this.setData({
                totalPrice: totalPrice
            })
        }
        this.getMyAdress();
    },
    getMyAdress() {
        let _this = this
        wx.getStorage({
            key: 'userAddress',
            success: function(res) {
                if (res.data && res.data.length > 0) {
                    _this.setData({
                        userAddress: res.data
                    })
                }
            },
            fail: (err) => {
                wx.showModal({
                    title: '提示',
                    content: '您还没有备用的收货地址',
                })
            }
        })
    },
    radioChange: function(e) {
        var userAddress = this.data.userAddress;
        for (var i = 0, len = userAddress.length; i < len; ++i) {
            if (i == e.detail.value) {
                userAddress[i].checked = i == e.detail.value;
                this.setData({
                    selectIndex: i
                })
            }
            userAddress[i].checked = i == e.detail.value
        }
        this.setData({
            userAddress: userAddress,
        });
    },
    submitOrder() {
        let totalPrice = this.data.totalPrice;
        if (app.globalData.userInfo.score < totalPrice) {
            wx.showModal({
                content: '您的积分低于商品总价。请适量购买，或联系管理员',
                showCancel: false,
            });
            return
        }
        let index = this.data.selectIndex;
        if (index === "") {
            wx.showModal({
                content: '请选择配送地址',
                showCancel: false,
            });
            return
        }
        let submitData = this.formatSubmitData()
        let _this = this
        this.startAuth(function() {
            wx.showLoading({
                title: '订单提交中',
            })
            const db = wx.cloud.database()
            //是否需要输入密码
            db.collection('order_list').add({
                data: submitData,
                success: res => {
                    // 在返回结果中会包含新创建的记录的 _id
                    let _id = res.data;
                    //减去用户的金币
                    let score = parseFloat(app.globalData.userInfo.score) - _this.data.totalPrice;
                    app.globalData.userInfo.score = score
                    const db = wx.cloud.database()
                    db.collection('userInfo').doc(app.globalData.userInfo._id).update({
                        data: {
                            score: score,
                        },
                        success: res => {
                            console.log(res)
                        }
                    })
                    let list = [];
                    _this.data.shopList.forEach(item => {
                        list.push(item.product_id);
                    })
                    /////测试云函数 批量操作
                    // console.log(list);
                    // wx.cloud.callFunction({
                    //     name: 'update',
                    //     data: {
                    //         db: "product_list",
                    //         parameter: {
                    //             _id: db.command.in(list)
                    //         },
                    //         todo: {
                    //             saledNum: 10
                    //         }
                    //     },
                    //     success: res => {
                    //         console.log(111, res);
                    //     },
                    //     fail: err => {
                    //         wx.showToast({
                    //             icon: 'none',
                    //             title: '调用失败',
                    //         })
                    //         console.error('[云函数] [sum] 调用失败：', err)
                    //     }
                    // })
                    /////////////////
                    let shopCarInfo = wx.getStorageSync('shopCarInfo');
                    shopCarInfo = shopCarInfo.shopList.filter(function(item) {
                        return !item.active;
                    });
                    wx.setStorageSync('shopCarInfo', {
                        shopList: shopCarInfo
                    });
                    wx.hideLoading();
                    wx.redirectTo({
                        url: '/pages/msg/msgSuccess',
                    })
                },
                fail: err => {
                    wx.showToast({
                        icon: 'none',
                        title: '提交失败：' + err,
                        mask: true
                    })
                    console.error('[数据库] [新增记录] 失败：', err)
                }
            })
        })
    },
    formatSubmitData() {
        let index = this.data.selectIndex;
        let userAddress = this.data.userAddress[index];
        let shopList = this.data.shopList
        let submitData = {
            buyer: app.globalData.openid,
            complete_time: "",
            consignee_time: "",
            order_time: new Date(),
            pay_time: "",
            status: 4,
            consignee: {
                address: userAddress.address,
                name: userAddress.name,
                phone: userAddress.phone,
                post_code: userAddress.post_code
            },
            goods_list: []
        };
        shopList.forEach(item => {
            submitData.goods_list.push({
                id: item.product_id,
                micro_img: item.show_img,
                name: item.name,
                buyNumber: item.buyNumber,
                parameter: {
                    name: item.parameter.name,
                    price: item.parameter.price
                }
            })
        })
        return submitData;
    },
    startAuth(cb) {
        const startSoterAuthentication = () => {
            wx.startSoterAuthentication({
                requestAuthModes: [AUTH_MODE],
                challenge: 'test',
                authContent: '小程序示例',
                success: (res) => {
                    wx.showToast({
                        title: '认证成功'
                    })
                    cb && cb()
                },
                fail: (err) => {
                    console.error(err)
                    wx.showModal({
                        title: '失败',
                        content: '认证失败',
                        showCancel: false
                    })
                    return false
                }
            })
        }

        const checkIsEnrolled = () => {
            wx.checkIsSoterEnrolledInDevice({
                checkAuthMode: AUTH_MODE,
                success: (res) => {
                    console.log(res)
                    if (parseInt(res.isEnrolled) <= 0) {
                        wx.showModal({
                            title: '错误',
                            content: '您暂未录入指纹信息，请录入后重试',
                            showCancel: false
                        })
                        return false
                    }
                    startSoterAuthentication();
                },
                fail: (err) => {
                    console.error(err)
                    return false
                }
            })
        }

        wx.checkIsSupportSoterAuthentication({
            success: (res) => {
                console.log(res)
                checkIsEnrolled()
            },
            fail: (err) => {
                console.error(err)
                wx.showModal({
                    title: '错误',
                    content: '您的设备不支持指纹识别',
                    showCancel: false
                })
                return false
            }
        })
    }
})